package cn.iocoder.yudao.module.exam.service.exam;

import cn.iocoder.yudao.module.exam.controller.admin.paper.vo.PaperRespVO;
import cn.iocoder.yudao.module.exam.service.paper.PaperService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.exam.controller.admin.exam.vo.*;
import cn.iocoder.yudao.module.exam.dal.dataobject.exam.ExamDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.exam.dal.mysql.exam.ExamMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.exam.enums.ErrorCodeConstants.*;

/**
 * 考试 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ExamServiceImpl implements ExamService {

    @Resource
    private ExamMapper Mapper;

    @Resource
    private PaperService paperService;

    @Override
    public Long create(ExamSaveReqVO createReqVO) {
        // 插入
        ExamDO  examDO= BeanUtils.toBean(createReqVO, ExamDO.class);
        PaperRespVO paper = paperService.getPaper(createReqVO.getPaperId());
        examDO.setPaperInfo(paper);
        Mapper.insert(examDO);
        // 返回
        return examDO.getId();
    }

    @Override
    public void update(ExamSaveReqVO updateReqVO) {
        // 校验存在
        validateExists(updateReqVO.getId());
        // 更新
        ExamDO updateObj = BeanUtils.toBean(updateReqVO, ExamDO.class);
        PaperRespVO paper = paperService.getPaper(updateReqVO.getPaperId());
        updateObj.setPaperInfo(paper);
        Mapper.updateById(updateObj);
    }

    @Override
    public void delete(Long id) {
        // 校验存在
        validateExists(id);
        // 删除
        Mapper.deleteById(id);
    }

    private void validateExists(Long id) {
        if (Mapper.selectById(id) == null) {
            throw exception(_NOT_EXISTS);
        }
    }

    @Override
    public ExamDO get(Long id) {
        return Mapper.selectById(id);
    }

    @Override
    public PageResult<ExamDO> getPage(ExamPageReqVO pageReqVO) {
        return Mapper.selectPage(pageReqVO);
    }

}